export default function (el, { moveArea = el, cursor = 'move' } = {}) {
  moveArea.style.cursor = cursor

  moveArea.addEventListener('mousedown', (e) => {
    const selection = window.getSelection()
    selection.removeAllRanges()

    const { clientX: _x, clientY: _y } = e
    const { left: _left, top: _top } = getPosition(el)

    let move = requestAnimationFrame
      ? function (e) {
          requestAnimationFrame(() => {
            el.style.left = `${_left + e.clientX - _x}px`
            el.style.top = `${_top + e.clientY - _y}px`
          })
        }
      : function (e) {
          el.style.left = `${_left + e.clientX - _x}px`
          el.style.top = `${_top + e.clientY - _y}px`
        }

    function selectPrevent(e) {
      e.preventDefault()
    }

    function moveStop() {
      document.removeEventListener('mousemove', move)
      document.removeEventListener('mouseup', moveStop)
      document.removeEventListener('selectstart', selectPrevent)
    }

    document.addEventListener('selectstart', selectPrevent)
    document.addEventListener('mouseup', moveStop)
    document.addEventListener('mousemove', move)
  })
}

function getPosition(el) {
  const s = el.currentStyle || window.getComputedStyle(el, null)

  if (s.left === 'auto' || s.top === 'auto') {
    console.warn(`[Az-move]: Expect a positioning element，but get an element with position '${s.position}'`)
    el.style.position = 'absolute'
  }

  if (s.left.match(/%/g)) {
    var left = document.body.clientWidth * (s.left.replace(/%/g, '') / 100)
    var top = document.body.clientHeight * (s.top.replace(/%/g, '') / 100)
  } else {
    var left = +s.left.replace(/px/g, '')
    var top = +s.top.replace(/px/g, '')
  }

  return { left, top }
}
